package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.vo.DishVO;
import com.sky.vo.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Set;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: DishController
 *
 * @AUTHOR: zhang
 * DATE: 2023/11/23
 * DESCRIPTION :菜品信息表现层接口
 */
@Slf4j
@Api(tags = "B端-菜品信息表现层接口") //@Api:用户描述类的相关信息
@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Resource
    private DishService dishService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 清理缓存
     */
    private void clearDishCache() {
        //查询所有满足DISH_CACHE::*模板的KEY(要删除掉)
        Set keys = redisTemplate.keys("DISH_CACHE::*");
        //基于delete方法将要删除的Key组成的单列集合作为参数传递,即可删除!
        redisTemplate.delete(keys);
    }

    @ApiOperation("菜品分页")
    @GetMapping("/page")
    public Result<PageResult> getPage(DishPageQueryDTO dto){
        PageResult result = dishService.getPage(dto);
        return Result.success(result);
    }

    /**
     * 新增菜品
     * @param dishDTO 新增的菜品信息
     * @return Result
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result insertDish(@RequestBody DishDTO dishDTO){
        dishService.insertDish(dishDTO);
        //清理缓存
        clearDishCache();
        return Result.success();
    }
    @ApiOperation("根据id查询菜品信息")
    @GetMapping("/{id}")
    public Result<DishVO> selectDishById(@PathVariable Long id){
        DishVO dishVO = dishService.selectDishById(id);
        return Result.success(dishVO);
    }
    @ApiOperation("修改菜品信息")
    @PutMapping
    public Result updateDish(@RequestBody @Valid DishDTO dishDTO){
        log.info("【修改菜品信息】");
        dishService.updateDish(dishDTO);
        //清理缓存
        clearDishCache();
        return Result.success();
    }

    @ApiOperation("修改菜品状态")
    @PostMapping("/status/{status}")
    public Result updateDishStatus(@PathVariable Integer status,Long id){
        log.info("【修改菜品状态】");
        dishService.updateDishStatus(status,id);
        //清理缓存
        clearDishCache();
        return Result.success();
    }

    @ApiOperation("批量删除菜品状态")
    @DeleteMapping
    public Result deleteBatchDish(@RequestParam List<Long> ids){
        dishService.deleteBatchDish(ids);
        //清理缓存
        clearDishCache();
        return Result.success();
    }

    @GetMapping("/list")
    public Result<List<Dish>> selectDishByCategoryId(Long categoryId){
        List<Dish> dishes = dishService.selectDishByCategoryId(categoryId);
        return Result.success(dishes);
    }
}
